package com.lecture.junit.tdd.example;

import exception.PasswordReuseException;

/**
 * Security manager, which contains logic for managing passwords in a secure
 * manner.
 * 
 * @author Denis Kulagin (denis.kulagin@db.com)
 * 
 */
public class AccountSecurityManager {
	public final static int PASSWORD_REUSE_DENIED_RANGE = 24;

	private IAccount account;

	public AccountSecurityManager(IAccount account) {
		this.account = account;
	}

	/**
	 * Changes user password.
	 * 
	 * @param newPassword
	 *            new password
	 * @throws PasswordReuseException
	 *             if password could be reused
	 */
	public void changePassword(String newPassword)
			throws PasswordReuseException {
		if (wasPasswordUsedBefore(newPassword, PASSWORD_REUSE_DENIED_RANGE)) {
			throw new PasswordReuseException("User can't reuse "
					+ PASSWORD_REUSE_DENIED_RANGE + " previous passwords.");
		} else {
			account.setPassword(newPassword);
		}
	}

	/**
	 * Checks, if password was one of the N previously used passwords (N =
	 * range).
	 * 
	 * @param password
	 *            new password
	 * @param range
	 *            tested range
	 * @return true, if password was one of the N previously used passwords;
	 *         false otherwise
	 */
	private boolean wasPasswordUsedBefore(String password, int range) {
		String[] oldPasswords = account.getOldPasswordList();

		for (int i = oldPasswords.length - 1; i >= 0
				&& i > oldPasswords.length - 1 - range; i--) {
			if (oldPasswords[i].equals(password)) {
				return true;
			}
		}

		return false;
	}
}
